package com.tql.kingdee.util;

import com.alibaba.fastjson.JSON;
import okhttp3.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkhttpUtil {
    private static final OkHttpClient WEB_CLIENT = initClient();
    private static OkHttpClient initClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(100, TimeUnit.SECONDS)
                .readTimeout(100, TimeUnit.SECONDS)
                .writeTimeout(100, TimeUnit.SECONDS)
                .build();
    }
    public static String post(String url,String requestBody, HashMap<String,String> headers)
    {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody);

        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        if(null!=headers&&headers.size()>0)
        {
            for(Map.Entry<String,String> header:headers.entrySet())
            {
                requestBuilder.addHeader(header.getKey(), header.getValue());
            }
        }

        String response= doRequest(WEB_CLIENT.newCall(requestBuilder.build()));
        return response;
    }


    private static String doRequest(Call call) {
        String result = "{}";

        Response okResponse = null;
        try {
            okResponse = call.execute();
            result = okResponse.body().string();
        } catch (Exception e) {
            System.out.println("OPENAPI请求失败: " + JSON.toJSONString(call.request())+"-e-"+e.toString());
        } finally {
            if (null != okResponse && null != okResponse.body()) {
                okResponse.body().close();
            }
        }

        return result;
    }

}
